"""
重写ModelViewSet的部分方法，为响应数据添加'code'、'msg'两个字段，方便前端程序做相应处理。
"""
from django.utils.timezone import now

from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
# 历史记录
# from action.models import Action, History


class MyModelViewSet(viewsets.ModelViewSet):
    def create(self, request, *args, **kwargs):
        """
        创建一个模型的实例.
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['created_by'] = request.user
        serializer.validated_data['last_edited_by'] = request.user
        serializer.save()
        headers = self.get_success_headers(serializer.data)
        context = {
            'code': status.HTTP_201_CREATED,
            'msg': '创建成功！',
            'data': serializer.data
        }

        return Response(context, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        """
        检索一个模型的实例.
        """
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        context = {
            'code': status.HTTP_200_OK,
            'msg': '检索成功！',
            'data': serializer.data
        }
        return Response(context)

    def update(self, request, *args, **kwargs):
        """
        更新一个模型的实例.
        """
        partial = kwargs.pop('partial', False)
        instance = self.get_object()

        serializer = self.get_serializer(
            instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.validated_data['last_edited_by'] = request.user
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        context = {
            'code': status.HTTP_200_OK,
            'msg': '更新成功！',
            'data': serializer.data
        }

        return Response(context)

    def destroy(self, request, *args, **kwargs):
        """
        销毁模型实例.
        """
        instance = self.get_object()

        # 永久删除
        # self.perform_destroy(instance)

        # 临时删除
        instance.deleted = 1
        instance.save()
        context = {
            'code': status.HTTP_204_NO_CONTENT,
            'msg': '删除成功！',
            'data': ''
        }
        return Response(context, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        """
        列出查询集.
        """
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            context = {
                'code': status.HTTP_200_OK,
                'msg': '成功！',
                'data': serializer.data
            }
            return self.get_paginated_response(context)

        serializer = self.get_serializer(queryset, many=True)
        context = {
            'code': status.HTTP_200_OK,
            'msg': '成功！',
            'data': serializer.data
        }
        return Response(context)
